package com.kalaqia.im.library.msg;

import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMChatManager;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.MainThreadDisposable;

/**
 * function:
 * project:kalaqia
 * describe:
 * created owner:kalaqia 421407393@qq.com
 * created date:2017/8/16 16:39
 */
//<editor-fold desc="version update log">
// updare owner:kalaqia  421407393@qq.com
// update datetime:2017/8/16 16:39 
// update remark:
//</editor-fold>
public class EMMessageObservable extends Observable<List<EMMessage>> {

    private EMChatManager manager;

    public EMMessageObservable(EMChatManager manager) {
        this.manager = manager;
    }

    @Override
    protected void subscribeActual(Observer<? super List<EMMessage>> observer) {
        EMMessageDisposable disposable = new EMMessageDisposable(manager, observer);
        observer.onSubscribe(disposable);
        manager.addMessageListener(disposable);
    }

    private final class EMMessageDisposable extends MainThreadDisposable implements EMMessageListener {

        private final EMChatManager manager;
        private final Observer<? super List<EMMessage>> observer;

        public EMMessageDisposable(EMChatManager manager, Observer<? super List<EMMessage>> observer) {
            this.manager = manager;
            this.observer = observer;
        }

        @Override
        public void onMessageReceived(List<EMMessage> list) {
            if (!isDisposed()) {
                observer.onNext(list);
            }
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> list) {

        }

        @Override
        public void onMessageRead(List<EMMessage> list) {

        }

        @Override
        public void onMessageDelivered(List<EMMessage> list) {

        }

        @Override
        public void onMessageRecalled(List<EMMessage> list) {

        }

        @Override
        public void onMessageChanged(EMMessage emMessage, Object o) {

        }

        @Override
        protected void onDispose() {
            manager.addMessageListener(null);
        }
    }


}
